package com.study.web.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.study.common.utils.ResponseUtil;
import com.study.web.context.SpringContextUtil;

/**
 * 非法参数过滤器
 * 当请求参数带有非法参数则抛出异常
 * @author yaojinshan
 * @since 2017-11-17 13:49
 *
 */
public class ParamsIllegalFilter implements Filter {
	/**
	 * 不需要非法字符校验的参数数组 unValidationParamsSet set 集合
	 */
	private static Set<String> unValidationParamsSet = new HashSet<String>();
	
	static Pattern illegalCharPattern = Pattern.compile("[@!#\"\'\\$%\\^&\\*]");

    /**
     * Default constructor. 
     */
    public ParamsIllegalFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		@SuppressWarnings("unchecked")
		Map<String,String[]> parameterMap = request.getParameterMap();//通过request.getParameterMap()获取到的值只能是一个数组 
		String[] keyValueArray = null;
		Set<String> keySet = parameterMap.keySet();
		if(!keySet.isEmpty()){
			Matcher matcher = null;
			String paramKey = null;
			for (Iterator<String> iterator = keySet.iterator(); iterator.hasNext();) {
				 paramKey = iterator.next();
				 if(unValidationParamsSet.contains(paramKey)){
					 continue;
				 }else{
					 keyValueArray = parameterMap.get(paramKey);
					 for(String stemp : keyValueArray){
						 matcher = illegalCharPattern.matcher(stemp);
						 if(matcher.find()){
							 String msg = "参数值:" + paramKey + "存在敏感字符,请核对后提交！";
							 Map<String,Object> resultMap = new HashMap<String, Object>();
							 resultMap.put("msg", msg);
							 resultMap.put("result", ResponseUtil.RES_FAIL);
							 response.getWriter().write(JSON.toJSONString(resultMap));
							 return;
						 }
					 }
				 }
				//如果包含特殊字符 则直接抛出异常
				 keyValueArray = parameterMap.get(paramKey);
				 for(String stemp : keyValueArray){
					 if(SpringContextUtil.findSensitiveWord(stemp)){
						 String msg = "参数值:" + paramKey + "存在敏感字符,请核对后提交！";
						 if("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))){
							 response.setContentType("text/html;charset=utf-8");
							 Map<String,Object> resultMap = new HashMap<String, Object>();
							 resultMap.put("msg", msg);
							 resultMap.put("result", ResponseUtil.RES_FAIL);
							 response.getWriter().write(JSON.toJSONString(resultMap));
							 return;
						 }else{
							 request.setAttribute("errorMsg", msg);
							 request.getRequestDispatcher("/error.jsp").forward(request, response);
						 }
						 //throw new IllegalDataException("参数值:" + paramKey + "存在敏感字符,请核对后提交！");
					 }
				 }
			}
		}
		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		unValidationParamsSet.add("desc");
		unValidationParamsSet.add("email");
		unValidationParamsSet.add("companyIntro");
		unValidationParamsSet.add("description");
		unValidationParamsSet.add("companyScope");
		unValidationParamsSet.add("integralBuyPrizeName");
		unValidationParamsSet.add("permission");//权限字段
		unValidationParamsSet.add("linkUrl");
		unValidationParamsSet.add("adName");
		unValidationParamsSet.add("keyValue");
		unValidationParamsSet.add("describe");//银行产品：描述
		unValidationParamsSet.add("yieldRate");//银行产品：预期收益
	}
	
}
